package com.huitone.gddw.controller.monitoring.environment;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huitone.gddw.log.Log;
import com.huitone.gddw.log.LogResult;
import com.huitone.gddw.log.LogType;
import com.huitone.gddw.service.dto.monitoring.environment.EnvDTO;
import com.huitone.gddw.service.monitoring.environment.ITomcatMonitorService;

/**
 * tomcat监控
 * @author wuluodan
 *
 */
@Controller
@RequestMapping(value="tomcatMon")
public class TomcatMonitorController {

	private final static Logger LOGGER = Logger.getLogger(TomcatMonitorController.class);
	
	@Autowired
	private ITomcatMonitorService tomcatMonitorService;
	
	/**
	 * 查询
	 * @param page
	 * @param request
	 * @return QueryPage
	 */
	@ResponseBody
	@RequestMapping(value="query")
	@Log(logType=LogType.SELECT, content="tomcat监控-查询tomcat监控列表")
	public List<Map<String, Object>> query(HttpServletRequest request) {
		try {
			List<Map<String, Object>> list = new ArrayList<>();
			List<EnvDTO> result = tomcatMonitorService.query();
			for (EnvDTO envDTO : result) {
				boolean isSame = false;
				for (Map<String, Object> map : list) {
					if (map.get("itemId").toString().equals(envDTO.getItemId())) {
						map.put(envDTO.getKey(), envDTO.getValue());
						isSame = true;
						break;
					}
				}
				if (!isSame) {
					Map<String, Object> map = new HashMap<>();
					map.put("itemId", envDTO.getItemId());
					map.put("warnCount", envDTO.getWarnCount());
					map.put("clock", envDTO.getClock());
					map.put("lastTime", envDTO.getClock() == null ? "" : new Date((long)envDTO.getClock() * 1000));
					map.put(envDTO.getKey(), envDTO.getValue());
					list.add(map);
				}
			}
			return list;
		} catch (Exception e) {
			LOGGER.error("查询tomcat监控列表信息出现异常：" + e.getMessage(), e);
			request.setAttribute("logResult", LogResult.EXCEPTION);
			return null;
		}
	}
	
}
